/*
 * Josh Lindoo
 * Login ID : lind6441
 * CS-102, Winter 2013
 * Programming Assignment 5
 * Prog5Client class: Client for program 5 -- controls program flow
 */

import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import javax.swing.*;

public class Prog5 extends JFrame {
	
	//instantiate database
	private static Database database = new Database();
	
	//container and panel fields
	private Container container; //top-level container
	private JPanel menuPanel; //panel for menu
	private JPanel outputPanel; //panel for output area
	
	//menu buttons
	final int TOTAL_BTNS = 7;
	
	final int BROWSE = 0; //const for print
	final int SEARCH = 1; //const for search
	final int ADD_MOVIE = 2; //cost for adding movie
	final int ADD_SHOW = 3; //const for adding showing
	final int VALIDATE = 4; //const for validate db
	final int WRITE_TO_DISK = 5; //const for write to disk
	final int REINITIALIZE = 6; //const for reinitialize db
	
	private JButton[] menuBtns = new JButton[TOTAL_BTNS]; //array of btns
	private String[] btnLabels = {
			"Browse Movies and Showings",
			"Search Movies",
			"Add Movie",
			"Add Show",
			"Validate Database",
			"Save Database",
			"Reinitialize Database"
			}; //string values for button names
	
	//text area and scroll pane
	private static JTextArea outputTextArea; //text area
	private JScrollPane scrollPane; //scroll pane
	
	//constructor
	public Prog5(String windowTitle) {
		
		//set window title
		super(windowTitle);
		
		//get the content pane
		container = getContentPane();
		container.setLayout(new BoxLayout(container, BoxLayout.LINE_AXIS));
		
		//
		//instantiate menu panel
		//
		menuPanel = new JPanel();
		menuPanel.setLayout(new GridLayout(15,1));
		menuPanel.setBorder(BorderFactory.createCompoundBorder(
				BorderFactory.createTitledBorder(
						"Program Features"),
						BorderFactory.createEmptyBorder(10,10,10,10)
						));
		
		//instantiate menu buttons
		for(int index = 0; index < menuBtns.length; index++) {
			menuBtns[index] = new JButton(btnLabels[index]);
			menuBtns[index].setPreferredSize(new Dimension(200,25));
		}
		
		//add buttons to menu panel
		for(int index = 0; index < menuBtns.length; index++)
			menuPanel.add(menuBtns[index]);
		
		//add panel to top-level container
		container.add(menuPanel);
		
		//instantiate event handler for menu buttons
		btnHandler menuBtnHandler = new btnHandler();
		
		//register event handler
		for(int index = 0; index < menuBtns.length; index++)
			menuBtns[index].addActionListener(menuBtnHandler);
		
		//
		//instantiate output panel
		//
		outputPanel = new JPanel();
		outputPanel.setLayout(new BoxLayout(outputPanel, BoxLayout.PAGE_AXIS));
		outputPanel.setBorder(BorderFactory.createCompoundBorder(
				BorderFactory.createTitledBorder(
						"Output"),
						BorderFactory.createEmptyBorder(10,10,10,10)
						));
		
		//instantiate scrollpane and text area
		outputTextArea = new JTextArea();
		outputTextArea.setEditable(false);
		outputTextArea.setFont(new Font("Sans", Font.BOLD, 12));
		outputTextArea.setMargin(new Insets(10,10,10,10));
		
		scrollPane = new JScrollPane(outputTextArea);
		
		outputTextArea.setText(
				"--- Program Info ---\n\n" +
				"Author: Josh Lindoo\n" +
				"Login ID: lind6441\n" +
				"Class: CS-102, Winter 2013\n" +
				"Assignment: Program 5\n\n" +
				"Special Note:\n\n" +
				"Professor Huggins,\n\n" +
				"Thanks for making this my favorite CS class so far!\n" +
				"I look forward to any future classes I get to take with " +
				"you.\nYou're a very gifted instructor.\n\n" +
				"Have a great B-Section Term!\n\n" +
				"- Josh");
		
		//add output area to pane
		outputPanel.add(scrollPane);
		
		//add panel to container
		container.add(outputPanel);
		
		//set frame size and visibility
		setSize(850,700);
		setVisible(true);

	}
	
	private class btnHandler implements ActionListener {
		
		public void actionPerformed(ActionEvent event) {
			
			//browse
			if(event.getSource() == menuBtns[BROWSE]) {
				database.printAll();
			} 
			//search
			else if(event.getSource() == menuBtns[SEARCH]) {
				
				//get user input
				String input = JOptionPane.showInputDialog("What movie are " +
						"you looking for?");
				database.searchMovies(input);
			}
			//add movie
			else if(event.getSource() == menuBtns[ADD_MOVIE]) {
				
				Scanner inputScanner; //scanner for user input
				
				//store user input
				String input = JOptionPane.showInputDialog(
					"Please input movie data in the" +
					"following form: \n" +
					"unique ID/title/time in mins/rating"
					);
				
				//protect scanner from null string
				if(input.length() == 0) {
					JOptionPane.showMessageDialog(null, "No input..");
					return;
				}
				else {
					inputScanner = new Scanner(input);
				}
				
		    	database.usrAddMovie(inputScanner);

			}
			//add show
			else if(event.getSource() == menuBtns[ADD_SHOW]) {
				
				Scanner inputScanner; //scanner for user input
				
				//store user input
				String input = JOptionPane.showInputDialog(
					"Please input showing data in the" +
					"following form: \n" +
					"unique ID/yyyymmdd/hhmm"
					);
				
				//protect scanner from null string
				if(input.length() == 0) {
					JOptionPane.showMessageDialog(null, "No input..");
					return;
				}
				else {
					inputScanner = new Scanner(input);
				}
				
		    	database.usrAddShow(inputScanner);

			}
			//validate
			else if(event.getSource() == menuBtns[VALIDATE]) {
				
				//store user input
				String input = JOptionPane.showInputDialog(
					"Input date in the form yyyymmdd:"
					);
				//get confirmation and store in result
				int result = JOptionPane.showConfirmDialog(null, "Are you " +
						"sure you want to use this date string?\n\n \"" 
						+ input + "\"\n\n" +
						"All showings before this date will be removed.");
				
				if(result == 0) { //yes
					database.validateDB(input);
				}
				else { //no or cancel
					JOptionPane.showMessageDialog(null, "Operation " +
							"cancelled..");
					return;
				}
			}
			//save
			else if(event.getSource() == menuBtns[WRITE_TO_DISK]) {
				
				//get user input
				Scanner inputScanner;
				
				String input = JOptionPane.showInputDialog("Input names of " +
					"Movie and Show files separated by a space:"
					);
				
				//protect scanner from null string
				if(input.length() == 0) {
					JOptionPane.showMessageDialog(null, "No input..");
					return;
				}
				else {
					inputScanner = new Scanner(input);
				}
				
				database.writeToDisk(inputScanner.next(), inputScanner.next());
				
				JOptionPane.showMessageDialog(null, "Database files saved to" +
						" the same directory as program.");
				
			}
			//reinitialize
			else if(event.getSource() == menuBtns[REINITIALIZE]) {
				
				//get user input
				Scanner inputScanner;
				
				String input = JOptionPane.showInputDialog("Input names of " +
					"Movie and Show files separated by a space:"
					);
				
				//protect scanner from null string
				if(input.length() == 0) {
					JOptionPane.showMessageDialog(null, "No input..");
					return;
				}
				else {
					inputScanner = new Scanner(input);
				}
				
				//storeArgs is a str array of the movie and show file names
				String[] storeArgs = {inputScanner.next(),inputScanner.next()};
				initialize(storeArgs);
				
				JOptionPane.showMessageDialog(null, "Initialization " +
						"complete!");
			}
		}
	}

	public static void main(String[] args) {
		
		initialize(args); //initialize db from args
		Prog5 menuGUI = new Prog5("Prog 5 Menu");
		menuGUI.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

	}
	
	
	/*
	 * Method: initialize
	 * Purpose: check file names and create scanners to pass to db for
	 *  		initialization
	 * Parameters:
	 * 		Scanner console:	scanner of user input
	 * Returns: void
	 */
	
	public static void initialize(String[] fileNames) {
		
		Scanner movieFile = null; //movie file
		Scanner showFile = null; //show file
		
		// ***** create movieFile Scanner
		try {
			movieFile = new Scanner(new File(fileNames[0]));
		}
		//if there is no parameter for showings file
		catch (ArrayIndexOutOfBoundsException exc) { 
			//if there is nothing at args[0], there weren't any parameters
			JOptionPane.showMessageDialog(null, "No arguments were passed " +
					"in for the movies and showings files.");
			return;
		}
		//if the file doesn't exist or it fails to open
		catch (FileNotFoundException exc) {
			JOptionPane.showMessageDialog(null, "Movie file could not " +
					"be opened..");
			return;
		}
		// ***** end
		
		// ***** create showFile Scanner
		try {
			showFile = new Scanner(new File(fileNames[1]));
		}
		//if there is no parameter for showings file
		catch (ArrayIndexOutOfBoundsException exc) {
			JOptionPane.showMessageDialog(null, "No parameter entered " +
					"for showings list file name.");
			return;
		}
		//if the file doesn't exist or it fails to open
		catch (FileNotFoundException exc) {
			JOptionPane.showMessageDialog(null, "Showing file could not " +
					"be opened..");
			return;
		}
		// ***** end
		
		database.removeAll();
		database.storeMovies(movieFile); //store movies
		database.storeShowings(showFile); //store showings
	}
	
	
	/*
	 * Method: setOutputText
	 * Purpose: set output panel text
	 * Parameters:
	 * 		boolean reset: whether to concatinate or not
	 * 		string text: text to add
	 * Returns: void
	 */
	public static void setOutputText(boolean reset, String text) {
		if(reset)
			outputTextArea.setText(text);
		else
			outputTextArea.setText(outputTextArea.getText() + text);
	}
}
